package com.rest.demo.io;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * @author Administrator
 * @decription 管道流实现两个线程之间的通信
 * @Date 2018-02-01 16:29
 */
public class PipedStreamDemo {

    public static void main(String[] args) throws IOException {
        final PipedOutputStream outputStream = new PipedOutputStream();
        final PipedInputStream inputStream = new PipedInputStream(outputStream);

        new Thread(() -> {
            try {
                outputStream.write("thread output".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(() -> {
            int b = -1;
            byte[] buff = new byte[1024];
            try {
                while((b = inputStream.read(buff)) != -1) {
                    System.out.println(new String(buff,0,b));
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
